package com.ybe.util;

import com.sun.net.httpserver.HttpExchange;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

public class CommonUtil {

    public static int parseInt(String s) {
        return Integer.parseInt(s);
    }

    public  static String getQueryParam(String rawQuery, String name) {
        if (rawQuery == null || rawQuery.isEmpty()) {
            return null;
        }
        for (String p : rawQuery.split("&")) {
            int idx = p.indexOf('=');
            if (idx < 0) {
                continue;
            }
            String k = decode(p.substring(0, idx));
            if (name.equals(k)) {
                return decode(p.substring(idx + 1));
            }
        }
        return null;
    }

    private static String decode(String s) {
        try {
            return java.net.URLDecoder.decode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return s;
        }
    }

    public static String readBody(HttpExchange ex) throws IOException {
        InputStream is = ex.getRequestBody();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int r;
        while ((r = is.read(buf)) != -1) {
            bos.write(buf, 0, r);
        }
        return bos.toString(StandardCharsets.UTF_8.name());
    }
}
